<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller {
    function __construct(){
        parent::__construct();
        $this->load->model('news_model', 'n');
        _c();
    }

    function index(){
        $data['result']  = $this->n->get_many_by(array('delete_flag' => UNDELETE_FLAG, 'draft' => UNACTIVE_FLAG));
        $data['tpl']     = 'admin/news/index';
        $this->load->view('_layout/admin', $data);
    }

    function add(){
        $this->_update();
    }

    function edit($id = 0){
        $this->_update($id);
    }

    function _update($id = 0){
        $id = intval($id);
        $edit_flag = $id != 0 ? true : false;

        if ($_POST){
            $id = intval($this->input->post('id'));
            $info = array(
                'title'        => trim($this->input->post('title')),
                'category_id'  => intval($this->input->post('category')),
                'intro'        => trim($this->input->post('intro')),
                'content'      => trim($this->input->post('content')),
                'update_date'  => date('Y-m-d H:i:s', time()),
                'draft'        => UNACTIVE_FLAG
            );
            $result = $this->n->update($id, $info);

            if ($edit_flag){
                $data['msg'] = 'Lưu tin tức thành công';
            } else {
                $data['msg'] = 'Thêm mới tin tức thành công';
            }
        }

        if ($edit_flag){
            $data['data'] = $this->n->get($id);
        } else {
            //Check draft
            $exist = $this->n->get_by(array('draft' => ACTIVE_FLAG, 'user_id' => $_SESSION['admin']['id']));
            if (count($exist) > 0){
                $data['data'] = $exist;
            } else {
                $draft = array('draft' => ACTIVE_FLAG, 'user_id' => $_SESSION['admin']['id'], 'update_date' => date('Y-m-d H:i:s'), 'create_date' => date('Y-m-d H:i:s'));
                $this->n->insert($draft);
                $data['data'] = $draft;
            }
        }

        //Category
        $cate_data = $this->db->get(TBL_NEWS_CATEGORY)->result();
        foreach($cate_data as $key => $value){
            $cate[$value->category_id] = $value->title;
        }

        $data['category'] = $cate;
        $data['tpl'] = 'news/edit';
        $this->load->view('_layout/admin', $data);
    }

    function delete(){
        if ($_POST){
            $id = $this->input->post('id');
            if (is_array($id)){
                $id = array($id);
            }
            $result = $this->n->update_many($id, array('delete_flag' => DELETE_FLAG));
            echo $result;
        }
    }
}